<?php
/**
 * Descript:后台用户管理
 * User: blue
 * Date: 2018/10/1 21:05
 */

namespace app\api\controller\v1;

use app\api\model\User as UserModel;
use app\library\base\BaseController;
use app\library\except\ParmasException;
use app\library\server\TokenS;
use rabbit\base\Regular;
use think\facade\Request;

class Manager extends BaseController
{
    protected $validname="\\app\\api\\validate\\UserValid";
    protected $modelName="\\app\\api\\model\\User";

    protected $beforeActionList=[
        'checkAuth'=>['only'=>'addc,updatec,delc,user_assign_group,change_password']
    ];
    /* 用户授权组 */
    public function user_assign_group(){
        $userid=Request::post('user_id');
        $groupids=Request::post('group_ids');
        Regular::positive($userid);
        Regular::checkIds($groupids);
        $groupidsArr=explode(',',$groupids);
        $user=UserModel::get($userid);
        /*先删除中间表所有数据,然后再增加相关的数据*/
        $user->GroupM2M()->detach();
        $res=$user->GroupM2M()->attach($groupidsArr);
        return successStatus('ok',$res);
    }

    /* 修改密码*/
    public function change_password(){
        //获取token->去缓存中查找信息->找到id->更新数据.
        $id=TokenS::getTokenFromCache('id');
        $userObj=UserModel::get($id);

        $data=Request::post();
        $check=password_verify($data['oldPwd'],$userObj->password);
        if(!$check){
            Throw new ParmasException('旧密码错误');
        }
        $userObj->password=$data['password'];
        $res=$userObj->save();
        return [
            'status'=>'ok',
            'data'=>$res
        ];
    }
}